#!/usr/bin/env python
#=======================================================================
#
#          FILE: create_header.py
#         USAGE: ./create_header.py <file>
#   DESCRIPTION: Create file header
#  REQUIREMENTS: N/A
#          BUGS: N/A
#         NOTES: N/A
#        AUTHOR: Ali Ayoub
#         EMAIL: ali@mellanox.com
#       COMPANY: N/A
#       CREATED: 09.17.2010-16:52:22
#      REVISION: 1.0
#=======================================================================

import sys
import os
import popen2
import time

SNAME = os.path.basename(sys.argv[0])
USAGE = "%s <file>" % (SNAME)
EXAMPLE = "%s %s" % (SNAME, "fofo.sh")

# You may change the following two lines, nobody's perfect
AUTHOR = "Ali Ayoub"
AUTHOR_EMAIL = "ali@mellanox.com"

debug = "--debug" in sys.argv
if debug:
	sys.argv.remove("--debug")

log = "--log" in sys.argv
if log:
	sys.argv.remove("--log")

def vprint(msg):
	if debug > 0:
		sys.stdout.write(str(msg) + '\n')
		if log > 0:
			fd = open(LOG, 'a')
			now =  time.strftime("%Y.%m.%d-%H.%M.%S", time.localtime())
			fd.write("%s:%s: %s\n" % (now, str(sys.argv), msg))
			fd.close()


def run_cmd(cmd, retry = 0, nap = 1):
	p = popen2.Popen4(cmd)
	rc = p.wait()
	if rc:
		out = "-E- FAILED"
	else:
		out = p.fromchild.read()
	vprint("-V- cmd [%s], rc [%s], out_len [%d], retry [%d]" % \
		(str(cmd), str(rc), len(out), retry))
	if (rc or len(out) == 0) and retry > 0:
		retry = retry -1
		try:
			time.sleep(nap)
		except:
			return (rc, out)
		return run_cmd(cmd, retry, nap)

	return (rc, out)


template="								\n\
#!_LANG_BIN_								\n\
#=======================================================================\n\
#									\n\
#          FILE: _FILE_							\n\
#         USAGE: _USAGE_						\n\
#   DESCRIPTION: _DESCRIPTION_						\n\
#  REQUIREMENTS: _REQUIREMENTS_						\n\
#          BUGS: _BUGS_							\n\
#         NOTES: _NOTES_						\n\
#        AUTHOR: _AUTHOR_	 					\n\
#         EMAIL: _EMAIL_						\n\
#       COMPANY: _COMPANY_						\n\
#       CREATED: _DATE_							\n\
#      REVISION: _REVISION_						\n\
#=======================================================================\n\
"

# main
def main():
	rc = 0
	date = time.strftime("%m.%d.%Y-%H:%M:%S", time.localtime())
	na = "N/A"
	tbd = "TBD"
        if len(sys.argv[1:]) != 1:
                print "USAGE: %s" % USAGE
                print "EXAMPLE: %s" % EXAMPLE
                return 1

	fn = sys.argv[1]

	if not os.path.exists(fn):
		print "-E- file not found %s" % fn
		return 2


	header = template
	_LANG_BIN_= "/bin/bash -"
	if   fn.endswith(".py") or not os.system("head -n1 %s | grep -q -i python" % fn):
		_LANG_BIN_ = "/usr/bin/env python"
	elif fn.endswith(".pl") or not os.system("head -n1 %s | grep -q -i perl" % fn):
		_LANG_BIN_ = "!/usr/bin/perl -w"
	else:
		vprint("default _LANG_BIN_ to bash")

	header = header.replace("_LANG_BIN_", _LANG_BIN_)

	_FILE_ = os.path.basename(fn)
	header = header.replace("_FILE_", _FILE_)

	_USAGE_ = "./" + _FILE_
	usage  = os.popen(fn + " --help 2>&1  | grep -i usage | cut -d' '  -f3- | sed -e 's,^\ ,'',g'").read().strip()
	if len(usage):
		_USAGE_ = _USAGE_ + " " + usage
	header = header.replace("_USAGE_", _USAGE_)

	_DESCRIPTION_ = tbd
	header = header.replace("_DESCRIPTION_", _DESCRIPTION_)

	_REQUIREMENTS_ = tbd
	header = header.replace("_REQUIREMENTS_", _REQUIREMENTS_)

	_BUGS_ = na
	header = header.replace("_BUGS_", _BUGS_)

	_NOTES_ = na
	header = header.replace("_NOTES_", _NOTES_)

	_AUTHOR_ = AUTHOR
	header = header.replace("_AUTHOR_", _AUTHOR_)

	_EMAIL_ = AUTHOR_EMAIL
	header = header.replace("_EMAIL_", _EMAIL_)

	_COMPANY_ = na
	header = header.replace("_COMPANY_", _COMPANY_)

	_DATE_ = date
	header = header.replace("_DATE_", _DATE_)

	_REVISION_ = "1.0"
	header = header.replace("_REVISION_", _REVISION_)

	print header 

	vprint("-V- done [rc %d]" % rc)
	return rc

if __name__ == '__main__':
	try:
		rc = main()
	except Exception, e:
		rc = 2
		print ""
		print "-E- Interrupted! %s" % str(e)
		print "-E- Abort."
	sys.exit(rc)

